package com.pronosticos.portal.utils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.NestedNullException;

/**
 * @author Larry Ruiz, 3/16/11
 */
public class JsonUtils {
    public static Map<String, Object> transform(Object object, String... campos) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (String campo : campos) {
            try {
                map.put(campo, BeanUtils.getProperty(object, campo));
            } catch (NestedNullException e) {
                map.put(campo, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }

    public static List<Map<String, Object>> transform(List<?> objects, String... campos) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Object item : objects) {
            list.add(transform(item, campos));
        }
        return list;
    }

    public static List<List<String>> transformList(List<?> objects, String... campos) {
        List<List<String>> listFinal = new ArrayList<List<String>>();
        List<String> list;
        for (Object item : objects) {
            list = new ArrayList<String>();
            for (String campo : campos) {
                try {
                    list.add(BeanUtils.getProperty(item, campo));
                } catch (NestedNullException e) {
                    list.add(null);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            listFinal.add(list);
        }
        return listFinal;
    }

    public static Map<Object, Object> transformToCatalog(List<?> objects, String key, String value) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        for (Object item : objects) {
            try {
                Object oKey = BeanUtils.getProperty(item, key);
                Object oValue = BeanUtils.getProperty(item, value);
                map.put(oKey, oValue);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }


}
